package com.project.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("login")
    public String login(String userName, String pwd, HttpServletRequest req){
        UserBean user =userService.login(userName, pwd);
        if (user!=null){
            req.getSession().setAttribute("loginUser",user);
            return "ok";
        }

        return "no";
    }

    @RequestMapping("getLoginUser")
    public UserBean getLoginUser(HttpServletRequest req){
        return (UserBean) req.getSession().getAttribute("loginUser");
    }

    @RequestMapping("findByItem")
    public IPage<UserBean> findByItem(Integer pageNO, String userName){
        return userService.findByItem(pageNO, userName);
    }


    @RequestMapping("add")
    public String add(UserBean user, Integer[] roleIdArray){
        boolean flag = userService.add(user, roleIdArray);
        if (flag){
            return "ok";
        }
        return "no";
    }
    @RequestMapping("del")
    public String del(Integer id, HttpServletRequest req){
        UserBean loginUser = (UserBean) req.getSession().getAttribute("loginUser");
        boolean flag = userService.del(id,loginUser);
        if (flag){
            return "ok";
        }
        return "no";
    }
    @RequestMapping("findById")
    public UserBean findById(Integer id){
       return userService.findById(id);
    }

    @RequestMapping("updateRoles")
    public String updateRoles(Integer id,Integer[] roleId){
        userService.updateRoles(id, roleId);
        return "ok";
    }
    @RequestMapping("updatePwd")
    public String updatePwd( HttpServletRequest req, String pwd){
        UserBean user = (UserBean) req.getSession().getAttribute("loginUser");
        if (!user.getPwd().equals(pwd)) {
            userService.updatePwd(user.getId(), pwd);
            return "ok";
        } else {
            return "no";
        }
    }
}
